package com.appspot.MercerBroker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.base.Throwables;


public class InternalServlet extends HttpServlet 
{
	private static final long serialVersionUID = 261614542067384L;

	
	@Override
	public void doGet(  final HttpServletRequest req, 
			    		final HttpServletResponse resp ) throws IOException 
	{
        try 
        {	
        	resp.setContentType( "text/plain" );
        	
        	if( !req.getRemoteAddr().matches("^127\\.0\\.0\\.1") && 
        		!req.getRemoteAddr().matches("^musmlib\\.org"))
        	{
        		//resp.sendError( HttpServletResponse.SC_FORBIDDEN );
            	resp.getOutputStream().println( "External usage forbidden: " 
            			+ req.getRemoteAddr() );
        		
        		return;
        		
        	}//if

        	resp.getOutputStream().println( runCmd( 
        			new String[]{"cat", "/etc/hostname"} ));

        	resp.getOutputStream().println( runCmd( 
        			new String[]{"uname", "-v"} ));
        	
        	resp.getOutputStream().println( runCmd( 
        			new String[]{"df", "-h"} ));
            
        	resp.getOutputStream().println( runCmd( 
        			new String[]{"uptime"} ));
        	
        } 
        catch( final InterruptedException err) 
        {
        	Throwables.propagate(err);
        	
        }//try
        
	}//method	

	
	private String runCmd( final String[] cmd ) throws IOException,
													   InterruptedException
	{
    	ProcessBuilder probuilder = new ProcessBuilder( cmd );

    	Process process = probuilder.start();

    	InputStream inStream = process.getInputStream();
    	InputStreamReader inStreamRdr = new InputStreamReader(inStream);
    	BufferedReader br = new BufferedReader(inStreamRdr);

    	StringBuilder resultsTotal = new StringBuilder();
    	
    	String results;
    	
    	while( (results = br.readLine()) != null ) 
    	{
    		resultsTotal.append( results );
    		resultsTotal.append( "\n" );

    	}//while

    	process.waitFor();
    	
    	return resultsTotal.toString();
		
	}//method
	
	
}//class
